package com.codesuc.aichat.userFavorite.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.codesuc.aichat.userFavorite.entity.UserFavorite;
import com.codesuc.aichat.userFavorite.mapper.UserFavoriteMapper;
import com.codesuc.aichat.userFavorite.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Date;

/**
* @Author: ZhangGongMing
* @CreateTime: 2025/09/23 12:56
* @Description: UserFavorite业务实现类
* @Version: 1.0
*/
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {

    @Autowired
	private UserFavoriteMapper userFavoriteMapper;

    @Override
    public boolean addUserFavoriteRole(Long userId, Long roleId) {
        // 检查是否已经收藏
        if (isUserFavoriteRole(userId, roleId)) {
            return false; // 已经收藏，不能重复收藏
        }
        
        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setUserId(userId);
        userFavorite.setRoleId(roleId);
        userFavorite.setCreateTime(new Date());
        
        return this.save(userFavorite);
    }

    @Override
    public boolean removeUserFavoriteRole(Long userId, Long roleId) {
        LambdaQueryWrapper<UserFavorite> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果userId为空，从当前登录用户获取
        if (userId == null) {
            if (StpUtil.isLogin()) {
                userId = StpUtil.getLoginIdAsLong();
            } else {
                return false; // 未登录且未提供userId，无法删除
            }
        }
        
        queryWrapper.eq(UserFavorite::getUserId, userId)
                   .eq(UserFavorite::getRoleId, roleId);
        
        return this.remove(queryWrapper);
    }

    @Override
    public Page<UserFavorite> getUserFavoriteRolesPage(Long userId, Integer pageNo, Integer pageSize) {
        Page<UserFavorite> page = new Page<>(pageNo, pageSize);
        
        LambdaQueryWrapper<UserFavorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserFavorite::getUserId, userId)
                   .orderByDesc(UserFavorite::getCreateTime);
        
        return this.page(page, queryWrapper);
    }

    @Override
    public boolean isUserFavoriteRole(Long userId, Long roleId) {
        LambdaQueryWrapper<UserFavorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserFavorite::getUserId, userId)
                   .eq(UserFavorite::getRoleId, roleId);
        
        return this.count(queryWrapper) > 0;
    }

}